import asyncio

from aiohttp import web
import queue
import config
import type
from imgLoader.ImgLoader import ImgLoader
from imgLoader.VolumeLoader import VolumeLoader
from imgLoader.WatchingLoader import WatchingLoader
from share import img_loader_dict, watching_dict, watching_dicom_queue_dict
from type import EnumViewType
import time

# 创建 aiohttp 应用
app = web.Application()


# HTTP 路由处理
async def index(request):
    try:
        json_request = await request.json()
    except:
        print('err')
    return web.Response(text="Hello, this is the HTTP server!", content_type='text/html')


async def api_endpoint(request):
    return web.json_response({"message": "This is a JSON response from the HTTP API"})


def get_client_id(request):
    client_id = request.headers.get('socket_io_client_id')
    return client_id


async def load_give_path_dicom(request):
    json_request = await request.json()
    dicom_folder_path = json_request['dicom_folder_path']
    client_id = get_client_id(request)
    await init_img_loader(client_id, dicom_folder_path)
    response = web.json_response({
        "message": "ok",
    })
    return response


def get_img_loader(client_id):
    return img_loader_dict[client_id]


async def init_img_loader(client_id, dicom_folder_path):
    if client_id in img_loader_dict:
        print(f'error: 重复的id')
        return
    img_loader = ImgLoader(client_id, dicom_folder_path)
    img_loader_dict[client_id] = img_loader
    await  img_loader.load_dicom_at_once()

    watching_loader = WatchingLoader(dicom_folder_path, img_loader, client_id)
    watching_dict[client_id] = watching_loader
    q = queue.Queue()
    watching_dicom_queue_dict.setdefault(client_id, q)
    print('create watching, and create watching queue', client_id)
    asyncio.create_task(img_loader.start_watch_queue())


async def set_size(request):
    client_id = get_client_id(request)
    json_request = await request.json()
    view_type = json_request['viewType']
    size = json_request['size']
    img_loader: ImgLoader = get_img_loader(client_id)
    match view_type:
        case EnumViewType.Stack.value:
            width = size['width']
            height = size['height']
            asyncio.create_task(img_loader.set_stack_size((height, width)))
        case EnumViewType.MPR.value:
            asyncio.create_task(img_loader.set_mpr_viewer_size(size))
        case EnumViewType.Volume.value:
            width = size['width']
            height = size['height']
            img_loader.set_volume_viewer_size((width, height))
            asyncio.create_task(img_loader.get_view(EnumViewType.Volume.value))
    return web.json_response({
        "message": "ok",
    })


async def set_3d_params(request):
    from connect import send_message
    client_id = get_client_id(request)
    json_request = await request.json()

    img_loader: ImgLoader = get_img_loader(client_id)
    ans = await img_loader.set_3d_params(json_request)
    await send_message(client_id, ans)
    return web.json_response(
        {
            "message": "ok",
        })


async def set_3d_direction(request):
    from connect import send_message
    client_id = get_client_id(request)
    json_request = await request.json()
    img_loader: ImgLoader = get_img_loader(client_id)
    ans = await img_loader.set_3d_direction(json_request)
    await send_message(client_id, ans)
    return web.json_response(
        {
            "message": "ok",
        })


async def handle_mip_setting(request):
    from connect import send_message
    client_id = get_client_id(request)
    json_request = await request.json()
    img_loader: ImgLoader = get_img_loader(client_id)
    await img_loader.handle_mip(json_request)
    return web.json_response(
        {
            "message": "ok",
        })


async def handle_play(request):
    client_id = get_client_id(request)
    json_request = await request.json()
    img_loader: ImgLoader = get_img_loader(client_id)
    asyncio.create_task(img_loader.handle_play(json_request))
    return web.json_response(
        {
            "message": "ok",
        })


async def handle_play_4d(request):
    client_id = get_client_id(request)
    json_request = await request.json()
    img_loader: ImgLoader = get_img_loader(client_id)
    asyncio.create_task(img_loader.handle_play(json_request, is_4d=True))
    return web.json_response(
        {
            "message": "ok",
        })


async def handle_pause(request):
    from connect import send_message
    client_id = get_client_id(request)
    img_loader: ImgLoader = get_img_loader(client_id)
    img_loader.handle_pause()
    return web.json_response(
        {
            "message": "ok",
        })


async def change_phase(request):
    client_id = get_client_id(request)
    img_loader: ImgLoader = get_img_loader(client_id)
    json_request = await request.json()
    await img_loader.handle_phase_change(json_request)
    return web.json_response(
        {
            "message": "ok",
        })


async def handle_performance(request):
    client_id = get_client_id(request)
    img_loader: ImgLoader = get_img_loader(client_id)
    json_request = await request.json()
    await img_loader.handle_performance(json_request)
    return web.json_response(
        {
            "message": "ok",
        })




# 设置 HTTP 路由
app.router.add_get('/addWatch', index)

app.router.add_get('/test', api_endpoint)





app.router.add_post('/loadPathDicom', load_give_path_dicom)
app.router.add_post('/setSize', set_size)

app.router.add_post('/set3dParams', set_3d_params)
app.router.add_post('/set3dDirection', set_3d_direction)

app.router.add_post('/mipSetting', handle_mip_setting)

app.router.add_post('/play', handle_play)
app.router.add_post('/play4d', handle_play_4d)

app.router.add_post('/pause', handle_pause)
app.router.add_post('/changePhase', change_phase)
app.router.add_post('/performance', handle_performance)
